import { sendEvent } from "@/utils/tracker";
import Image from "@/components/Image";
import { completeImgUrl } from "common/utils/utils";
import React, { CSSProperties, memo, useEffect, useRef } from "react";
import { useInViewport } from "ahooks";

export interface ImageProps{
  width: string,
  height?: string,
  ossFormatParam?: string;
  imageStyle?: CSSProperties;
}

function Item({
  width,
  height,
  ossFormatParam,
  imageStyle,
  data,
}: ImageProps & {data: API.CarouselAllResult}){
  const ref = useRef<HTMLDivElement>(null);
  const [inViewport] = useInViewport(ref);

  useEffect(() => {
    if(inViewport){
      sendEvent({
        category: 'AD_BANNER',
        action: 'visible',
        label: data.uuid,
        value: {
          uuid: data.uuid,
          title: data.title,
          url: data.url
        }
      });
    }
  }, [inViewport]);

  return <div key={data.uuid} ref={ref} onClick={()=>{
    if(data.url){
      window.open(data.url);
      sendEvent({
        category: 'AD_BANNER',
        action: 'click',
        label: data.uuid,
        value: {
          uuid: data.uuid,
          title: data.title,
          url: data.url
        }
      });
    }
  }} style={{
    cursor: data.url ? 'pointer' : 'initial'
  }}>
    <Image
      wrapperStyle={{
        width,
        height,
      }}
      className="inline-block"
      style={{
        width,
        height,
        ...imageStyle,
      }}
      src={completeImgUrl(data.img, ossFormatParam)}
    />
  </div>
}

export default memo(Item);
